package com.restfinder.user.model;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.hibernate.annotations.ForeignKey;

import lombok.Setter;

import lombok.Getter;

import com.restfinder.model.IEntity;

@Entity
@Table(name="roles")
public class Role implements IEntity {

	private static final long serialVersionUID = 1L;
	
	// -- Fields --

	@Id
	@GeneratedValue
	@Getter @Setter
	private long id;
	
	@Column(unique=true)
	@Getter @Setter
	private String code;
	
	@Getter @Setter
	private String name;
	
	@Getter @Setter
	private String description;
	
	@ManyToMany
	@JoinTable(name="rel_users_roles",
	 joinColumns=@JoinColumn(name="role_id"),
	 inverseJoinColumns=@JoinColumn(name="user_id")
	)
	@ForeignKey(name="rel_users_roles_fk_role_id")
	@Getter @Setter
	private List<User> users;
	
	// -- Methods --
	
	/**
	 * Checks if code start with "ROLE_" prefix 
	 */
	public boolean hasValidCode(){
		return this.code.startsWith("ROLE_");
	}
	
	@Override
	public boolean equals(Object obj) {
		if(this == obj) return true;
		if ((obj == null) || !(obj instanceof Role)) {
			return false;
		}
		Role objRole = (Role) obj;
		return objRole.getId() == this.id;		
	}

	@Override
	public String toString() {
		return "Role.id="+this.id;
	}

}
